<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>编辑钉钉配置</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
    <style>
        .mainBox {
            padding: 15px;
        }

        .main-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .layui-form-item {
            margin-bottom: 20px;
        }

        .form-tip {
            display: block;
            margin-top: 8px;
            color: #666;
            font-size: 12px;
            line-height: 1.5;
        }

        .form-tip i {
            color: #1E9FFF;
            margin-right: 4px;
        }

        .example-box {
            margin-top: 8px;
            padding: 10px;
            background: #f8f8f8;
            border-radius: 4px;
            border: 1px solid #eee;
            font-family: monospace;
            font-size: 12px;
            color: #333;
            white-space: pre-wrap;
            word-break: break-all;
        }

        .bottom {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px;
            background: #fff;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
            z-index: 99;
        }

        .button-container {
            text-align: center;
        }

        .button-container button {
            margin: 0 8px;
        }
    </style>
</head>

<body>
    <form class="layui-form" action="" lay-filter="dingtalk-config-edit">
        <div class="mainBox">
            <div class="main-container">
                <!-- 1. 配置名称（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">配置名称 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required|verifyName" autocomplete="off"
                            placeholder="请输入配置名称（如：运营通知机器人）" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>配置名称为唯一标识，不可与其他配置重复
                        </span>
                    </div>
                </div>

                <!-- 2. 机器人Token（必填） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">机器人Token <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="access_token" id="access_token" lay-verify="required|verifyToken"
                            autocomplete="off" placeholder="请输入钉钉机器人Token" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>Token从钉钉机器人Webhook地址提取（格式：XXX）
                        </span>
                       <div class="example-box">
Token提取示例：
Webhook地址：https://oapi.dingtalk.com/robot/send?access_token=abcdef1234567890abcdef1234567890
提取的Token：abcdef1234567890abcdef1234567890
                        </div>
                    </div>
                </div>

                <!-- 3. 加签密钥（非必填：为空则不更新） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">加签密钥 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" name="secret" id="secret" lay-verify="verifySecret" autocomplete="off"
                            placeholder="修改请输入位密钥" class="layui-input">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>仅开启加签时需填写，需为40位字母或数字
                        </span>
                    </div>
                </div>

                <!-- 5. 描述说明（非必填：为空则不更新） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">描述说明</label>
                    <div class="layui-input-block">
                        <textarea name="description" id="description" autocomplete="off" placeholder="修改请输入用途说明"
                            class="layui-textarea" rows="3"></textarea>
                    </div>
                </div>
                <!-- 5. 模板状态（单选，默认开启） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">模板状态 <span style="color: #ff4d4f;">*</span></label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="开启" lay-skin="tag" checked>
                        <input type="radio" name="is_active" value="0" title="关闭" lay-skin="tag">
                        <span class="form-tip">
                            <i class="layui-icon layui-icon-info"></i>
                            关闭状态的模板无法用于发送短信
                        </span>
                    </div>
                </div>
                <!-- 6. 排序号（默认0，非负整数） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="number" name="sort_num" id="sort_num" lay-verify="verifySort" lay-affix="number"
                            autocomplete="off" value="0" placeholder="数字越大，列表中显示越靠前" class="layui-input">
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部提交按钮区域 -->
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit
                    lay-filter="dingtalk-config-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" id="close-btn">
                    <i class="layui-icon layui-icon-close"></i>
                    关闭
                </button>
            </div>
        </div>
    </form>

    <!-- 引入依赖JS文件 -->
    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;

            // 基础配置
            const API_BASE_URL = apiConfig.baseUrl;
            const AUTH_TOKEN = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");
            const urlParams = new URLSearchParams(window.location.search);
            const CONFIG_ID = urlParams.get('id'); // 编辑的钉钉配置ID
            let initialData = {}; // 存储初始数据（用于对比变更）

            // 1. 页面初始化：加载配置详情
            if (CONFIG_ID) {
                loadConfigDetail(); // 加载配置详情并回显表单
            } else {
                layer.msg('配置ID不存在，无法编辑', { icon: 2, time: 2000 });
                setTimeout(() => parent.layer.close(parent.layer.getFrameIndex(window.name)), 2000);
            }

            // 加载钉钉配置详情并回显表单
            function loadConfigDetail() {
                const loading = layer.load(2, { shade: 0.3 });
                $.ajax({
                    url: `${API_BASE_URL}/dingding/dingtalk/${CONFIG_ID}/`,
                    dataType: 'json',
                    type: 'GET',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success && result.data) {
                            const data = result.data;
                            // 保存初始数据（统一转为字符串便于对比）
                            initialData = {
                                name: data.name || '',
                                access_token: data.access_token || '',
                                secret: data.secret || '',
                                description: data.description || '',
                                sort_num: data.sort_num?.toString() || '0',
                                is_active: data.is_active?.toString() || '1'
                            };

                            // 回显表单（密钥默认不显示，避免敏感信息泄露）
                            form.val("dingtalk-config-edit", {
                                name: initialData.name,
                                access_token: initialData.access_token,
                                secret: initialData.secret,
                                description: initialData.description,
                                sort_num: initialData.sort_num,
                                is_active: initialData.is_active
                            });
                            form.render(); // 重新渲染表单
                        } else {
                            const errorMsg = result.message || '加载配置详情失败';
                            layer.msg(errorMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401 ? '登录已过期，请重新登录' : '网络异常，加载失败';
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });
            }

            // 2. 表单验证规则
            form.verify({
                // 配置名称：非空+长度1-50
                verifyName: function (value) {
                    const trimValue = value.trim();
                    if (trimValue.length === 0) return "配置名称不能为空";
                    if (trimValue.length > 50) return "配置名称长度不能超过50个字符";
                },
                // 机器人Token：非空+格式校验（32-64位字母数字）
                verifyToken: function (value) {
                    const trimValue = value.trim();
                    if (trimValue.length === 0) return "机器人Token不能为空";
                    const reg = /^[a-zA-Z0-9]{32,64}$/;
                    if (!reg.test(trimValue)) return "Token格式错误，仅支持32-64位字母或数字";
                },
                // 加签密钥：格式校验（40位字母数字，仅当有值时校验）
                verifySecret: function (value) {
                    const trimValue = value.trim();
                    if (!trimValue) return;
                    const reg = /^[a-zA-Z0-9]{100}$/; // 钉钉加签密钥固定100位
                    if (trimValue.length > 100) return "配置名称长度不能超过100个字符";
                },
                // 排序号：非负整数
                verifySort: function (value) {
                    const num = parseInt(value);
                    if (isNaN(num) || num < 0 || num > 9999) {
                        return "排序号需为0-9999之间的非负整数";
                    }
                }
            });

            // 3. 检查数据是否变更
            function isDataChanged(currentData) {
                // 对比必填字段
                const compareFields = ['name', 'access_token','is_active'];
                for (let field of compareFields) {
                    const currentVal = currentData[field]?.trim() || '';
                    const initialVal = initialData[field]?.trim() || '';
                    if (currentVal !== initialVal) return true;
                }

                // 对比可选字段：加签密钥
                const currentSecret = currentData.secret?.trim() || '';
                const initialSecret = initialData.secret?.trim() || '';
                if (currentSecret && currentSecret !== initialSecret) return true;

                // 对比可选字段：描述说明
                const currentDesc = currentData.description?.trim() || '';
                const initialDesc = initialData.description?.trim() || '';
                if (currentDesc && currentDesc !== initialDesc) return true;

                // 对比可选字段：排序号（非空且与初始值不同则视为变更）
                const currentSort = currentData.sort_num?.trim() || '';
                const initialSort = initialData.sort_num?.trim() || '';
                if (currentSort && currentSort !== initialSort) return true;

                return false;
            }

            // 4. 表单提交事件
            form.on('submit(dingtalk-config-save)', function (data) {
                const currentData = data.field;

                // 检查是否有实际变更
                if (!isDataChanged(currentData)) {
                    layer.msg("未修改任何数据，无需提交", { icon: 3, time: 1500 });
                    return false;
                }

                // 处理提交数据
                const submitData = {
                    name: currentData.name.trim(),
                    access_token: currentData.access_token.trim(),
                    is_active: parseInt(currentData.is_active)
                };

                // 可选字段：非空才添加
                if (currentData.secret?.trim()) submitData.secret = currentData.secret.trim();
                if (currentData.description?.trim()) submitData.description = currentData.description.trim();
                if (currentData.sort_num?.trim()) submitData.sort_num = parseInt(currentData.sort_num.trim());

                // 发送更新请求
                const loading = layer.load(2, { shade: 0.3, shadeClose: false });
                $.ajax({
                    url: `${API_BASE_URL}/dingding/dingtalk/${CONFIG_ID}/`,
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'PATCH',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success || result.code === 200) {
                            layer.msg(result.message || '钉钉配置更新成功', {
                                icon: 1,
                                time: 1500
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table");
                            });
                        } else {
                            let errorMsg = result.message || '更新失败，请重试';
                            if (result.data && typeof result.data === 'object') {
                                const firstErrorKey = Object.keys(result.data)[0];
                                if (firstErrorKey) errorMsg = result.data[firstErrorKey][0];
                            }
                            layer.msg(errorMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401
                            ? '登录已过期，请重新登录'
                            : `网络异常（${xhr.status}），更新失败`;
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) {
                            setTimeout(() => parent.window.location.href = '../../../login.html', 2000);
                        }
                    }
                });

                return false; // 阻止默认提交
            });

            // 5. 关闭按钮事件
            $('#close-btn').on('click', function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            // 6. 页面关闭前提示未提交的修改
            window.onbeforeunload = function (e) {
                const currentData = form.val("dingtalk-config-edit");
                if (isDataChanged(currentData)) {
                    const message = "当前页面有未提交的修改，关闭后将丢失，是否确认？";
                    e.returnValue = message;
                    return message;
                }
            };
        });
    </script>
</body>

</html>